package com.sun.dingDing.utils;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class GetSign {
    public static String getSign(){
        try {
            String uri = "https://oapi.dingtalk.com/robot/send?access_token=bc1c26788d73f092a7b72abe221a1d4522f0a1e758e60ba7e5a8d23df685c484";
            //String uri = "https://oapi.dingtalk.com/robot/send?access_token=224f787c5fbd0950e983341d26a84d43434b470ef8e78dbeb3351d03503333e8";
            Long timestamp = System.currentTimeMillis();
            String secret = "this is secret";

            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
            //return uri + "&timestamp=" + timestamp + "&sign=" + sign;
            return uri ;//+ "&timestamp=" + timestamp + "&sign=" + sign;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            return null;
        }
    }
    
}
